<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/9
 * Time: 17:40
 */
namespace app\admin\controller;
use think\Db;
use think\Request;
use app\admin\model\Admin as mAdmin;

class Admin extends AdminController
{
    public function _initialize()
    {
        parent::_initialize();
        $this->mAdmin = new mAdmin();
    }
    /**
     * 管理人员信息界面
     */
    public function admin_list()
    {
        $res = Db::name('admin')
            ->field('id, name, level, status')
            ->paginate();
        $page = $res->render();
        $data = array();

        for ($i = 0; $i < count($res); $i++) {
            $data[$i]['id'] = $res[$i]['id'];
            $data[$i]['name'] = $res[$i]['name'];
            $data[$i]['level'] = $res[$i]['level'];
            $data[$i]['status'] = $res[$i]['status'];
            // 查询管理员对应的角色信息
            $roles = Db::name('admin_role')
                ->alias('ar')
                ->field('r.name, r.id')
                ->join('role r', 'r.id = ar.rid', 'LEFT')
                ->where('ar.aid', $res[$i]['id'])
                ->select();
            $data[$i]['roles'] = $roles;
        }

        $this->assign('page',$page);
        $this->assign('data',$data);
        return $this->fetch('page/admin_list');
    }

    /**
     * 增加人员 界面
     */
    public function admin_add_page()
    {
        $roles = Db::table('free_role')->select();
        $this->assign('roles', $roles);
        return $this->fetch('page/admin_add');
    }

    /**
     * 添加人员动作
     */
    public function addAdmin()
    {
        $name = $_POST['username'];
        $pwd = password_hash($_POST['pass'], PASSWORD_DEFAULT);
        $role = $_POST['role'];         // 角色
//        $res = Db::execute("INSERT INTO `admin`(`name`, `password`, `level`, `status`) VALUES ('{$name}','{$pwd}',1,1)");
        $data = array('name' => $name, 'password' => $pwd, 'level' => 2, 'status' => 1);
        $res = Db::name("admin")
            ->insert($data);
        $lastId = Db::name('admin')->getLastInsID();

        if ($res){
            // 插入管理人员角色
            $data = array('aid' => $lastId, 'rid' => $role);
            $ruleRes = Db::name('admin_role')
                ->insert($data);
            return '添加成功';
        }else{
            return '添加失败';
        }
    }

    /**
     * 更新人员界面
     * */
    public function admin_edit($id)
    {
        // 查询该用户信息
        $res = Db::table('free_admin')->find($id);

        $this->assign('data', $res);
        return $this->fetch('page/admin_edit');
    }

    /**
     * 更新人员动作
     */
    public function update()
    {
        var_dump($_POST);
        $res = Db::name('admin')
            ->where('id', $_POST['id'])
            ->update(['name' => $_POST['username'],'level' => $_POST['level']]);

        if ($res){
            return '修改成功';
        }else{
            return '修改失败';
        }
    }

    /**
     * 更改密码
     */
    public function adminEditPassword()
    {
        $this->assign('uid', $_GET['id']);
        return $this->fetch('page/admin_edit_password');
    }
    public function savePassword()
    {
        $uid = $_POST['id'];
        $data = array(
        'password' => password_hash($_POST['pass'], PASSWORD_DEFAULT)
        );
        $res = Db::name('admin')
            ->where('id', $uid)
            ->update($data);
        if ($res) {
            return '修改成功';
        }
        return '修改失败';
    }

    /**
     * 删除人员 动作
     */
    public function remove()
    {
        $res = Db::table('free_admin')
            ->where('id', $_GET['id'])
            ->delete();
        if ($res) {
            return true;
        }
        return false;
    }

    /**
     * 修改人员状态
     */
    public function change_status()
    {
        if(!isset($_POST['status']) || !isset($_POST['id'])){
            $data = array(
                'code' => 410,
            );
        }else{
            $status = $_POST['status'] == 1?0:1;    // 取反

            $res = Db::name('admin')
                ->where('id', $_POST['id'])
                ->update(['status' => $status]);

            $data = array(
                'code' => 200,
                'status' => $status,
                'id' => $_POST['id'],
            );
        }
        return json($data);

    }

    /**
     * 修改人员角色 界面
     */
    public function admin_role($id)
    {
        $data = array();
        $res = Db::table('free_admin')
            ->alias('a')
            ->field('a.id as id, a.name as name, a.level, a.status, r.name as role, r.id as rid')
            ->join('admin_role ar','a.id = ar.aid', $type="LEFT")
            ->join('role r', 'ar.rid = r.id', $type='LEFT')
            ->where('a.id', $id)
            ->select();

        $allRole = Db::table('free_role')
            ->field('id, name')
            ->select();

        // 整合数据
        foreach($res as $v){
            $data['id'] = $v['id'];
            $data['name'] = $v['name'];
            $data['level'] = $v['level'];
            $data['status'] = $v['status'];
            $data['roles'][$v['rid']] =  $v['role'];
        }
        $data['allRole'] = $allRole;
        $this->assign('data', $data);
        return $this->fetch('page/admin_role');
    }

    // 修改人员角色 动作
    public function admin_role_add(){
        $adminId = $_POST['id'];
        $roleId = $_POST['roid'];
        $data = array();

        // 删除原有的角色信息,
        $delRes = Db::table('free_admin_role')
            ->where('aid',$adminId)
            ->delete();
        // 将新数据
        $num = count($roleId);
        for($i=0; $i<$num; $i++) {
            $data[$i] = array('rid' => $roleId[$i], 'aid' => $adminId);
        }
        $insRes = Db::table('free_admin_role')->insertAll($data);

        if ($delRes || $insRes){
            return '修改成功';
        }else{
            return '修改失败';
        }

    }

}
